import axios from 'axios';
import { Notification, MessageBox, Message, Loading } from 'element-ui';
import store from '@/store';
import { getToken } from '@/utils/auth';
// import https from 'https';
const qs = require('qs');

import errorCode from '@/utils/errorCode';
import cache from '@/plugins/cache';

// 是否显示重新登录
export let isRelogin = { show: false };

axios.defaults.headers['Content-Type'] = 'application/json';

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // httpsAgent: new https.Agent({
  //   rejectUnauthorized: false
  // }),
  // 超时
  timeout: 60000
});

if (process.env.NODE_ENV === 'development') {
  service.defaults.baseURL = '/testapi';
};

// request拦截器
service.interceptors.request.use(config => {
  // 如果是post/put请求，用qs.stringify序列化参数
  const isPostPut = config.method === 'put' || config.method === 'post';
  const isJson = config.headers['Content-Type'] === 'application/json';
  const isFile = config.headers['Content-Type'] === 'multipart/form-data';
  if (isPostPut && isJson) {
    config.data = JSON.stringify(config.data);
  };
  if (isPostPut && !isFile && !isJson) {
    config.data = qs.stringify(config.data, { arrayFormat: 'repeat' });
  };
  // 导出文件类型
  if (config.responseType && config.responseType == 'blob') {
    service.responseType = 'blob';
  };
  // Do something before request is sent
  /** 配置全屏加载 */
  if (config.loading !== false) {
    config.loading = Loading.service({
      lock: true,
      background: 'rgba(0, 0, 0, 0.6)',
      spinner: 'el-icon-loading',
      text: '请稍候...'
    });
  };

  /** 设置令牌 */
  let accessToken = getToken();
  if (accessToken) {
    config.headers['Authorization'] = `Bearer ${accessToken}`; // 让每个请求携带自定义token
  };

  /** 是否需要防止数据重复提交 */
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
  if (!isRepeatSubmit && isPostPut) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
      time: new Date().getTime()
    };
    const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 请求数据大小
    const limitSize = 5 * 1024 * 1024; // 限制存放数据5M
    if (requestSize >= limitSize) {
      console.warn(`[${config.url}]: ` + '请求数据大小超出允许的5M限制，无法进行防重复提交验证。');
      return config;
    };
    const sessionObj = cache.session.getJSON('sessionObj');
    if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
      cache.session.setJSON('sessionObj', requestObj);
    } else {
      const s_url = sessionObj.url;                  // 请求地址
      const s_data = sessionObj.data;                // 请求数据
      const s_time = sessionObj.time;                // 请求时间
      const interval = 1000;                         // 间隔时间(ms)，小于此时间视为重复提交
      if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
        const message = '数据正在处理，请勿重复提交';
        console.warn(`[${s_url}]: ` + message);
        return Promise.reject(new Error(message));
      } else {
        cache.session.setJSON('sessionObj', requestObj);
      };
    };
  };

  return config;
}, error => {
  console.log(error);
  Promise.reject(error);
});

// 响应拦截器
service.interceptors.response.use(
  async response => {
    // 关闭 loading
    await closeLoading(response);
    // 未设置状态码则默认成功状态
    const code = response.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || response.data.msg || errorCode['default'];
    // 二进制数据则直接返回
    if (response.request.responseType ===  'blob' || response.request.responseType ===  'arraybuffer') {
      return response.data;
    };
    if (code !== 200) {
      let _back = 'error';
      switch (code) {
        case 401:
          if (!isRelogin.show) {
            isRelogin.show = true;
            MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              isRelogin.show = false;
              store.dispatch('logoutAction').then(() => {
                location.href = '/index';
              });
            }).catch(() => {
              isRelogin.show = false;
            });
          };
          _back = '无效的会话，或者会话已过期，请重新登录。';
          break;
        case 500:
          Message({ message: msg, type: 'error' });
          _back = new Error(msg);
          break;
        case 601:
          Message({ message: msg, type: 'warning' });
          break;
        default:
          Notification.error({ title: msg });
          break;
      };
      return Promise.reject(_back);
    } else {
      return response.data;
    };
  },
  async error => {
    await closeLoading(error);
    let { message } = error;
    if (message == 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = `系统接口${message.substr(message.length - 3)}异常`;
    };
    Message({ message: message, type: 'error', duration: 5 * 1000 });
    return Promise.reject(error);
  }
);

/**
 * 关闭全局加载
 * 延迟200毫秒关闭，以免晃眼睛
 * @param target
 */
const closeLoading = (target) => {
  if (!target.config.loading) {
    return true;
  };
  return new Promise(resolve => {
    setTimeout(() => {
      target.config.loading.close();
      resolve();
    }, 200);
  });
};

export default function request (options) {
  return new Promise((resolve, reject) => {
    service(options).then(resolve).catch(reject);
  });
}
// export default service;